package com.eaero.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eaero.CommonResp;
import com.eaero.controller.workOrder.pojo.ReplyToolReqDetailRequest;
import com.eaero.entity.*;
import com.eaero.mapper.TraceWorkOrderDetailMapper;
import com.eaero.service.*;
import com.eaero.service.workorder.pojo.WorkOrderDetailRequset;
import com.eaero.util.IdGenUtils;
import com.eaero.vo.*;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zb
 * @since 2023-03-14
 */
@Service
public class TraceWorkOrderDetailServiceImpl extends ServiceImpl<TraceWorkOrderDetailMapper, TraceWorkOrderDetail> implements ITraceWorkOrderDetailService {

    private Gson gson = new Gson();

    @Autowired
    private ITraceToolService toolService;
    @Autowired
    private ITraceWarehouseService warehouseService;
    @Autowired
    private ITraceUserService userService;
    @Autowired
    private ITraceWorkOrderService workOrderService;

    @Override
    public CommonResp getWorkOrderDetail(WorkOrderDetailRequset orderDetailRequset) {

        return null;
    }

    @Override
    public void genWorkOrderDetail() {
        TraceWarehouse warehouse = warehouseService.getOne(Wrappers.<TraceWarehouse>lambdaQuery().eq(TraceWarehouse::getWarehouse, "warehouse1"));
        List<TraceWorkOrder> workOrderList = workOrderService.list();
        List<TraceTool> toolList = toolService.list(Wrappers.<TraceTool>lambdaQuery()
                .eq(TraceTool::getWarehouse, warehouse.getWarehouse()));
        List<TraceWorkOrderDetail> workDetailList = Lists.newArrayList();
        for (int i = 0; i < 4; i++) {
            TraceWorkOrderDetail orderDetail = new TraceWorkOrderDetail();
            orderDetail.setId(IdGenUtils.genId());
            orderDetail.setReqNo(workOrderList.get(1).getReqNo());
            orderDetail.setRid(RandomStringUtils.randomNumeric(12));
            orderDetail.setJcWorkorder(RandomStringUtils.randomNumeric(6));
            orderDetail.setJcSeq(StrUtil.format("000{}", i));
            orderDetail.setDtlSts("U");
            orderDetail.setWhsType(toolList.get(0).getWarehouse());
            orderDetail.setPn(toolList.get(i).getPartno());
            orderDetail.setReqPn(toolList.get(i).getPartno());
            orderDetail.setQty(200);
            orderDetail.setUnitofmeas("盒");
            orderDetail.setReqDate(LocalDateTime.now());
            orderDetail.setSndDate(LocalDateTime.now());
            orderDetail.setSndBy(StrUtil.format("{} {}", workOrderList.get(1).getReqUserCode(), workOrderList.get(0).getReqUserName()));
            orderDetail.setRemark(StrUtil.format("工单申请明细备注备注{}", RandomStringUtils.randomNumeric(12)));
            orderDetail.setMsg(null);
            orderDetail.setMsgUser(null);
            orderDetail.setMsgDate(null);
            orderDetail.setTailNo(workOrderList.get(1).getTailNo());
            orderDetail.setPartdescr(toolList.get(i).getPartdescr());
            orderDetail.setRcvBy(StrUtil.format("{} {}", "user003", "周詩涵"));
            orderDetail.setOnhandInfo(StrUtil.format("{}:{}", toolList.get(0).getWarehouse(), RandomUtil.randomNumbers(3)));
            orderDetail.setUptDate(null);
            orderDetail.setUptBy(null);
            orderDetail.setPickUser(null);
            orderDetail.setPickDate(null);
            workDetailList.add(orderDetail);
        }
        this.saveBatch(workDetailList);
    }

    @Override
    public CommonResp updateToolReqdetailPn(UpdateToolReqdetailPnRequest request) {
        List<UpdateToolReqdetailPn> updatePn = request.getUpdatePn();
        Set<String> rids = updatePn.stream().map(UpdateToolReqdetailPn::getRid).collect(Collectors.toSet());

        long ridCount = count(Wrappers.<TraceWorkOrderDetail>lambdaQuery().in(TraceWorkOrderDetail::getRid, rids));
        if (ridCount != rids.size()) {
            return CommonResp.buildFailMsg("没有该申请单明细");
        }

        long dtlStsCount = count(Wrappers.<TraceWorkOrderDetail>lambdaQuery()
                .in(TraceWorkOrderDetail::getRid, rids)
                .in(TraceWorkOrderDetail::getDtlSts, "N", "R"));
        if (dtlStsCount != rids.size()) {
            return CommonResp.buildFailMsg("仅草稿、提交申请状态的明细才能更改件号");
        }

        //Set<String> pns = updatePn.stream().map(UpdateToolReqdetailPn::getPn).collect(Collectors.toSet());
        //long toolCount = toolService.count(Wrappers.<TraceTool>lambdaQuery().in(TraceTool::getPartno, pns));
        //if (toolCount != pns.size()) {
        //    return CommonResp.buildFailMsg("更改的件号已存在");
        //}

        for (UpdateToolReqdetailPn updateToolReqdetailPn : updatePn) {
            update(Wrappers.<TraceWorkOrderDetail>lambdaUpdate()
                    .set(TraceWorkOrderDetail::getReqPn, updateToolReqdetailPn.getPn())
                    .set(TraceWorkOrderDetail::getQty, updateToolReqdetailPn.getQty())
                    .eq(TraceWorkOrderDetail::getRid, updateToolReqdetailPn.getRid())
            );
        }
        return CommonResp.buildSucsDataListMsg(null, "更新件号和数量成功！");
    }

    @Override
    public CommonResp updateWhsType(UpdateWhsTypeRequest request) {
        List<UpdateWhsType> updateWhs = request.getUpdateWhs();
        Set<String> rids = updateWhs.stream().map(UpdateWhsType::getRid).collect(Collectors.toSet());

        long ridCount = count(Wrappers.<TraceWorkOrderDetail>lambdaQuery().in(TraceWorkOrderDetail::getRid, rids));
        if (ridCount != rids.size()) {
            return CommonResp.buildFailMsg("没有该申请单明细");
        }

        long dtlStsCount = count(Wrappers.<TraceWorkOrderDetail>lambdaQuery().in(TraceWorkOrderDetail::getRid, rids).eq(TraceWorkOrderDetail::getDtlSts, "R"));
        if (dtlStsCount != rids.size()) {
            return CommonResp.buildFailMsg("提交申请状态的申请明细才能指定拣料仓库");
        }

        TraceWarehouse warehouse = warehouseService.getOne(Wrappers.<TraceWarehouse>lambdaQuery().eq(TraceWarehouse::getWarehouse, request.getWhsType()));
        if (ObjectUtil.isAllEmpty(warehouse)) {
            return CommonResp.buildFailMsg("没有该指定仓库");
        }

        for (UpdateWhsType updateWh : updateWhs) {
            update(Wrappers.<TraceWorkOrderDetail>lambdaUpdate()
                    .set(TraceWorkOrderDetail::getWhsType, request.getWhsType())
                    .eq(TraceWorkOrderDetail::getRid, updateWh.getRid()));
        }
        return CommonResp.buildSucsDataListMsg(null, "指定拣料仓库成功！");
    }

    @Override
    public List<WorkOrderDetail> getWorkOrderDetailByRid(List<String> rids) {
        return this.getBaseMapper().getWorkOrderDetailByRid(rids);
    }

    @Override
    public CommonResp getToolReqdetailSum(GetToolReqdetailSumRequest request) {
        List<GetToolReqdetailSumVo> getToolReqdetailSumVos = new ArrayList<>();
        List<TraceUser> users = userService.list();
        for (TraceUser user : users) {
            GetToolReqdetailSumVo getToolReqdetailSumVo = new GetToolReqdetailSumVo();

            getToolReqdetailSumVo.setTailNo("B-9527");
            getToolReqdetailSumVo.setRcvBy(StrFormatter.format("{} {}", user.getUserCode(), user.getUserName()));
            getToolReqdetailSumVo.setReqDate(DateUtil.formatDateTime(DateTime.now()));
            getToolReqdetailSumVo.setWhsType("STRGJX");
            getToolReqdetailSumVo.setReqNum(RandomUtil.randomEle(Lists.newArrayList(150, 200, 300)));
            getToolReqdetailSumVo.setClsNum(RandomUtil.randomEle(Lists.newArrayList(null, 34, 62)));
            getToolReqdetailSumVo.setUnNum(RandomUtil.randomEle(Lists.newArrayList(null, 15, 28)));
            getToolReqdetailSumVo.setIssueNum(RandomUtil.randomEle(Lists.newArrayList(null, 20, 30)));
            getToolReqdetailSumVos.add(getToolReqdetailSumVo);
        }
        return CommonResp.buildSucsDataListMsg(getToolReqdetailSumVos, "数据获取成功！");
    }

    @Override
    public CommonResp replyToolReqDetail(ReplyToolReqDetailRequest request) {
        List<String> ridList = request.getReplyDetail();
        boolean re = this.update(Wrappers.<TraceWorkOrderDetail>lambdaUpdate()
                .set(TraceWorkOrderDetail::getMsg, request.getMsg())
                .set(TraceWorkOrderDetail::getMsgUser, request.getUserCode())
                .set(TraceWorkOrderDetail::getMsgDate, DateUtil.format(new Date(), "yyyy-MM-dd"))
                .in(TraceWorkOrderDetail::getRid, ridList)
        );
        if(re){
            return  CommonResp.buildSuccessMsg("回复明细成功！");
        }
        return  CommonResp.buildSuccessMsg("回复明细失败！");
    }


  /*  @Override
    public List<RequisitionWorkDetail> getWorkOrderDetail(List<RequisitionWork> workOrder) {
        List<ToolInfo> allTool = toolService.getAllTool();
        List<UserInfo> userInfoAll = userInfoService.getUserInfoAll();
        ArrayList<String> stsStrList = Lists.newArrayList("N", "R", "P", "U", "B", "L", "I", "N", "R", "P", "U", "B", "L", "I", "N", "R", "P", "U", "B", "L", "I", "N", "R", "P", "U", "B", "L", "I", "N", "R", "P", "U", "B", "L", "I", "N", "R", "P", "U", "B", "L", "I");
        List<RequisitionWorkDetail> workDetailList = Lists.newArrayList();
        for (int i = 0; i < 6; i++) {
            RequisitionWorkDetail workDetail = new RequisitionWorkDetail();
            workDetail.setReqNo(workOrder.get(0).getReqNo());
            workDetail.setRid(RandomStringUtils.randomAlphanumeric(16));
            workDetail.setPn(allTool.get(i).getPartno());
            workDetail.setReqPn(allTool.get(i).getPartno());
            workDetail.setUptDate(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
            workDetail.setUptBy(workOrder.get(0).getUptBy());
            workDetail.setQty(RandomUtil.randomNumbers(2));
            workDetail.setUnitofmeas("个");
            workDetail.setJcSeq("JC3522");
            workDetail.setJcWorkorder("123456789");
            workDetail.setDtlSts(stsStrList.get(i));
            workDetail.setMsg(StrUtil.format("明细处理回复{}", RandomStringUtils.randomAlphanumeric(10)));
            workDetail.setMsgUser(workOrder.get(0).getUptBy());
            ThreadUtil.sleep(1000);
            workDetail.setMsgDate(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
            workDetail.setWhsType(allTool.get(i).getWarehouse());
            workDetail.setRemark(StrUtil.format("明细备注{}", RandomStringUtils.randomAlphanumeric(10)));
            workDetail.setTailNo("B-2697");
            workDetail.setPartdescr(allTool.get(i).getPartdescr());
            workDetail.setRcvBy(StrUtil.format("{} {}", userInfoAll.get(2).getUserCode(), userInfoAll.get(2).getUserName()));
            workDetail.setReqDate("2023-04-06");
            ThreadUtil.sleep(1000);
            workDetail.setSndDate(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
            workDetail.setSndBy(workOrder.get(0).getUptBy());
            workDetail.setOnhandInfo(StrUtil.format("{}:{}", allTool.get(i).getWarehouse(), RandomUtil.randomNumbers(3)));
            workDetailList.add(workDetail);
            ThreadUtil.sleep(1000);
        }
        for (int i = 0; i < 3; i++) {
            RequisitionWorkDetail workDetail = new RequisitionWorkDetail();
            workDetail.setReqNo(workOrder.get(1).getReqNo());
            workDetail.setRid(RandomStringUtils.randomAlphanumeric(16));
            workDetail.setPn(allTool.get(i).getPartno());
            workDetail.setReqPn(allTool.get(i).getPartno());
            workDetail.setUptDate(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
            workDetail.setUptBy(workOrder.get(1).getUptBy());
            workDetail.setQty(RandomUtil.randomNumbers(2));
            workDetail.setUnitofmeas("个");
            workDetail.setJcSeq("JC3522");
            workDetail.setJcWorkorder("123456789");
            workDetail.setDtlSts(stsStrList.get(i));
            workDetail.setMsg(StrUtil.format("明细处理回复{}", RandomStringUtils.randomAlphanumeric(10)));
            workDetail.setMsgUser(workOrder.get(1).getUptBy());
            ThreadUtil.sleep(1000);
            workDetail.setMsgDate(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
            workDetail.setWhsType(allTool.get(i).getWarehouse());
            workDetail.setRemark(StrUtil.format("明细备注{}", RandomStringUtils.randomAlphanumeric(10)));
            workDetail.setTailNo("B-2697");
            workDetail.setPartdescr(allTool.get(i).getPartdescr());
            workDetail.setRcvBy(StrUtil.format("{} {}", userInfoAll.get(2).getUserCode(), userInfoAll.get(2).getUserName()));
            workDetail.setReqDate("2023-04-06");
            ThreadUtil.sleep(1000);
            workDetail.setSndDate(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
            workDetail.setSndBy(workOrder.get(1).getUptBy());
            workDetail.setOnhandInfo(StrUtil.format("{}:{}", allTool.get(i).getWarehouse(), RandomUtil.randomNumbers(3)));
            workDetailList.add(workDetail);
            ThreadUtil.sleep(1000);
        }
        for (int i = 0; i < 3; i++) {
            RequisitionWorkDetail workDetail = new RequisitionWorkDetail();
            workDetail.setReqNo(workOrder.get(2).getReqNo());
            workDetail.setRid(RandomStringUtils.randomAlphanumeric(16));
            workDetail.setPn(allTool.get(i).getPartno());
            workDetail.setReqPn(allTool.get(i).getPartno());
            workDetail.setUptDate(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
            workDetail.setUptBy(workOrder.get(2).getUptBy());
            workDetail.setQty(RandomUtil.randomNumbers(2));
            workDetail.setUnitofmeas("个");
            workDetail.setJcSeq("JC3522");
            workDetail.setJcWorkorder("123456789");
            workDetail.setDtlSts(stsStrList.get(i));
            workDetail.setMsg(StrUtil.format("明细处理回复{}", RandomStringUtils.randomAlphanumeric(10)));
            workDetail.setMsgUser(workOrder.get(2).getUptBy());
            ThreadUtil.sleep(1000);
            workDetail.setMsgDate(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
            workDetail.setWhsType(allTool.get(i).getWarehouse());
            workDetail.setRemark(StrUtil.format("明细备注{}", RandomStringUtils.randomAlphanumeric(10)));
            workDetail.setTailNo("B-2697");
            workDetail.setPartdescr(allTool.get(i).getPartdescr());
            workDetail.setRcvBy(StrUtil.format("{} {}", userInfoAll.get(2).getUserCode(), userInfoAll.get(2).getUserName()));
            workDetail.setReqDate("2023-04-06");
            ThreadUtil.sleep(1000);
            workDetail.setSndDate(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
            workDetail.setSndBy(workOrder.get(2).getUptBy());
            workDetail.setOnhandInfo(StrUtil.format("{}:{}", allTool.get(i).getWarehouse(), RandomUtil.randomNumbers(3)));
            workDetailList.add(workDetail);
            ThreadUtil.sleep(1000);
        }
        for (int i = 0; i < 2; i++) {
            RequisitionWorkDetail workDetail = new RequisitionWorkDetail();
            workDetail.setReqNo(workOrder.get(3).getReqNo());
            workDetail.setRid(RandomStringUtils.randomAlphanumeric(16));
            workDetail.setPn(allTool.get(i).getPartno());
            workDetail.setReqPn(allTool.get(i).getPartno());
            workDetail.setUptDate(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
            workDetail.setUptBy(workOrder.get(3).getUptBy());
            workDetail.setQty(RandomUtil.randomNumbers(2));
            workDetail.setUnitofmeas("个");
            workDetail.setJcSeq("JC3522");
            workDetail.setJcWorkorder("123456789");
            workDetail.setDtlSts(stsStrList.get(i));
            workDetail.setMsg(StrUtil.format("明细处理回复{}", RandomStringUtils.randomAlphanumeric(10)));
            workDetail.setMsgUser(workOrder.get(3).getUptBy());
            ThreadUtil.sleep(1000);
            workDetail.setMsgDate(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
            workDetail.setWhsType(allTool.get(i).getWarehouse());
            workDetail.setRemark(StrUtil.format("明细备注{}", RandomStringUtils.randomAlphanumeric(10)));
            workDetail.setTailNo("B-2697");
            workDetail.setPartdescr(allTool.get(i).getPartdescr());
            workDetail.setRcvBy(StrUtil.format("{} {}", userInfoAll.get(2).getUserCode(), userInfoAll.get(2).getUserName()));
            workDetail.setReqDate("2023-04-06");
            ThreadUtil.sleep(1000);
            workDetail.setSndDate(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
            workDetail.setSndBy(workOrder.get(3).getUptBy());
            workDetail.setOnhandInfo(StrUtil.format("{}:{}", allTool.get(i).getWarehouse(), RandomUtil.randomNumbers(3)));
            workDetailList.add(workDetail);
            ThreadUtil.sleep(1000);
        }
        return workDetailList;
    }

    @Override
    public List<RequisitionWorkDetail> getWorkOrderDetailByWorkOrderCode(String workOrderCode) throws IOException {
        String json = new String(Files.readAllBytes(Paths.get("src/main/resources/workOrderDetails.json")));
        List<RequisitionWorkDetail> details = gson.fromJson(json, new TypeToken<List<RequisitionWorkDetail>>() {
        }.getType());
        ArrayList<RequisitionWorkDetail> result = Lists.newArrayList();
        for (RequisitionWorkDetail detail : details) {
            if (StrUtil.equals(detail.getReqNo(), workOrderCode)) {
                result.add(detail);
            }
        }
        return result;
    }

    private List<RequisitionWorkDetail> getWorkOrderDetailAll() throws IOException {
        String json = new String(Files.readAllBytes(Paths.get("src/main/resources/workOrderDetails.json")));
        List<RequisitionWorkDetail> details = gson.fromJson(json, new TypeToken<List<RequisitionWorkDetail>>() {
        }.getType());
        ArrayList<RequisitionWorkDetail> result = Lists.newArrayList();
        for (RequisitionWorkDetail detail : details) {
            result.add(detail);
        }
        return result;
    }

    @Override
    public List<RequisitionWorkDetailCollect> getRequisitionWorkDetailCollect() throws IOException {
        List<RequisitionWorkDetail> workOrderDetailAll = this.getWorkOrderDetailAll();
        List<RequisitionWorkDetailCollect> requisitionWorkDetailCollectList = Lists.newArrayList();
        for (int i = 0; i < 14; i++) {
            RequisitionWorkDetailCollect workDetailCollect = new RequisitionWorkDetailCollect();
            workDetailCollect.setTailNo(workOrderDetailAll.get(i).getTailNo());
            workDetailCollect.setRcvBy(workOrderDetailAll.get(i).getRcvBy());
            workDetailCollect.setReqDate(workOrderDetailAll.get(i).getReqDate());
            workDetailCollect.setWhsType(workOrderDetailAll.get(i).getWhsType());
            workDetailCollect.setReqNum(workOrderDetailAll.get(i).getQty());
            workDetailCollect.setClsNum("0");
            workDetailCollect.setUnNum("0");
            workDetailCollect.setIssueNum(StrUtil.format("1{}", i));
            requisitionWorkDetailCollectList.add(workDetailCollect);
        }
        return requisitionWorkDetailCollectList;
    }

    @Override
    public List<RequisitionWorkDetailCollect> getRequisitionWorkDetailCollectByTailNo(String tailNo) throws IOException {
        List<RequisitionWorkDetailCollect> requisitionWorkDetailCollect = this.getRequisitionWorkDetailCollect();
        ArrayList<RequisitionWorkDetailCollect> result = Lists.newArrayList();
        for (RequisitionWorkDetailCollect workDetailCollect : requisitionWorkDetailCollect) {
            if (StrUtil.equals(workDetailCollect.getTailNo(),tailNo)){
                result.add(workDetailCollect);
            }
        }
        return result;
    }*/
}
